package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.KaurConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.module.domain.Account;
import com.ruoyi.module.service.IAccountService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IAccountService accountService;
    @Autowired
    private ISysUserService userService;
    /**
     * 后管端登录方法
     *
     * @param loginBody 后管端登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 网页登录方法
     *
     * @param loginBody 网页登录信息
     * @return 结果
     */
    @Anonymous
    @PostMapping("/webLogin")
    public AjaxResult webLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody);
        Map map = new HashMap();
        map.put("token", token);
        ajax.put(Constants.Data, map);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUser().getUserId());
//        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        if (user.getDeptId() != null) {
            SysDept sysDept = deptService.selectDeptById(user.getDeptId());
            user.setLevel(sysDept.getLevel());
        }

        AjaxResult ajax = AjaxResult.success();
        //封装经销商（分公司ID）
        if (user.getCompanyId() != null) {
            SysDept sysDept = deptService.selectDeptById(user.getCompanyId());
            ajax.put("deptDistributor", sysDept);
            Account account = accountService.selectAccountByUserId(sysDept.getUserId());//分公司负责人
            ajax.put("account", account);
        }
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    @Anonymous
    @ApiOperation("小程序Code换取OpenId")
    @GetMapping("/appletGetOpenId")
    public AjaxResult appletGetOpenId(@RequestParam String code) {
        return AjaxResult.success().put("data", loginService.appletGetOpenId(code, KaurConstants.APPLET_APP_ID, KaurConstants.APPLET_APP_SECRET));
    }
}
